package com.redxun.util;

import java.util.regex.Pattern;

/**
 * @author: hj
 * @Description: xss过滤工具
 * @Date: Created in 2020/7/4.
 */
public class XssCleanRuleUtils {
    
    private static final String REG1 = "<script>(.*?)</script>";
    
    private static final String REG2 = "src[\r\n]*=[\r\n]*\\\'(.*?)\\\'";
    
    private static final String REG3 = "</script>";
    
    private static final String REG4 = "<script(.*?)>";
    
    private static final String REG5 = "eval\\((.*?)\\)";
    
    private static final String REG6 = "expression\\((.*?)\\)";
    
    private static final String REG7 = "javascript:";
    
    private static final String REG8 = "vbscript:";
    
    private static final String REG9 = "onload(.*?)=";
    
    private static final String REG10 = "onclick(.*?)=";
    
    private static final String REG11 = "onerror(.*?)=";
    
    private static final  Pattern[] SCRIPT_PATTERNS = {
            Pattern.compile(REG1, Pattern.CASE_INSENSITIVE),
            Pattern.compile(REG2, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            Pattern.compile(REG3, Pattern.CASE_INSENSITIVE),
            Pattern.compile(REG4, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            Pattern.compile(REG5, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            Pattern.compile(REG6, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            Pattern.compile(REG7, Pattern.CASE_INSENSITIVE),
            Pattern.compile(REG8, Pattern.CASE_INSENSITIVE),
            Pattern.compile(REG9, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            Pattern.compile(REG10, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
            Pattern.compile(REG11, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
    };
    
    public static String xssClean(String value) {
        if (value  !=  null) {
            value = value.replaceAll("\0|\n|\r", "");
            for (Pattern pattern : SCRIPT_PATTERNS) {
                value = pattern.matcher(value).replaceAll("");
            }
            //value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        }
        return value;
    }
}
